﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace RDJTProtocolServer
{
    class Program
    {
        static void Main(string[] args)
        {
            var server = new TcpListener(IPAddress.Parse("127.0.0.1"), 5000);
            server.Start();
            Console.WriteLine("Sever started yeey...");

            while (true)
            {
                // TODO: accept the client in a new thread!
                var client = server.AcceptTcpClient();

                Thread thread = new Thread(
                    () => HandleClient(client)
                );

                thread.Start();
            }
        }

        private static void HandleClient(TcpClient client)
        {
            var stream = client.GetStream();
            var buffer = new byte[client.ReceiveBufferSize];

            var streamCount = stream.Read(buffer, 0, buffer.Length);

            string message = Encoding.UTF8.GetString(buffer, 0, streamCount);

            var rdjtp = new Rdjtp(message);
            bool success = rdjtp.ExecuteRequest();

            if (success)
            {
                rdjtp.Response.Body = "Isn't this cool?";
            }

            //Console.WriteLine(rdjtp.Response.ToJson());
            //rdjtp.Response.Body

            //message += " - spiced-up by the server baby!";
            var payload = Encoding.UTF8.GetBytes(rdjtp.Response.ToJson());
            stream.Write(payload, 0, payload.Length);

            stream.Close();
            client.Close();
        }
    }
}
